package org.example.web.websocket;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ProgressSocket extends WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProgressSocket.class);
    private final Set<WebSocket> connections = Collections.synchronizedSet(new HashSet<>());

    public ProgressSocket(int port) {
        super(new InetSocketAddress(port));
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        connections.add(conn);
        LOGGER.info("新的前端连接已建立: {}", conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        connections.remove(conn);
        LOGGER.info("前端连接已关闭: {}", conn.getRemoteSocketAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        // 我们这里只做服务端到客户端的单向通知，所以忽略客户端消息
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        LOGGER.error("WebSocket发生错误", ex);
        if (conn != null) {
            connections.remove(conn);
        }
    }

    @Override
    public void onStart() {
        LOGGER.info("WebSocket服务器已在端口 {} 启动", getPort());
        setConnectionLostTimeout(100);
    }

    /**
     * 向所有连接的前端页面广播消息
     * @param message 要发送的消息
     */
    public void broadcast(String message) {
        synchronized (connections) {
            for (WebSocket conn : connections) {
                conn.send(message);
            }
        }
    }
} 